package com.jzy.gulimall.search.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.jzy.common.to.es.SkuEsTo;
import com.jzy.common.utils.R;
import com.jzy.gulimall.search.config.ElasticSearchConfig;
import com.jzy.gulimall.search.constant.EsConstant;
import com.jzy.gulimall.search.feign.ProductFeignService;
import com.jzy.gulimall.search.service.MallSearchService;
import com.jzy.gulimall.search.vo.AttrResponseVo;
import com.jzy.gulimall.search.vo.BrandRespVo;
import com.jzy.gulimall.search.vo.SearchParam;
import com.jzy.gulimall.search.vo.SearchResp;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jzy
 * @date 2020/9/14 12:58
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private ProductFeignService productFeignService;

    /**
     * 首页/搜索页  条件搜索
     */
    @Override
    public SearchResp search(SearchParam searchParam) {
        if (searchParam != null) {
            //1.动态构建出查询请求
            SearchRequest searchRequest = buildSearchRequest(searchParam);
            try {
                //2.执行检索请求
                SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
                //3.分析响应数据 封装成需要的格式
                return buildSearchResult(search, searchParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 首页/搜索页  条件搜索
     * 封装返回结果
     */
    private SearchResp buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResp searchResp = new SearchResp();
        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();
        //封装商品信息
        List<SkuEsTo> skuEsTos = new ArrayList<>();
        if (null != hits && hits.length > 0) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsTo skuEsTo = JSONUtil.toBean(sourceAsString, SkuEsTo.class);
                if (StringUtils.isNotBlank(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    if (skuTitle != null) {
                        Text[] fragments = skuTitle.fragments();
                        StringBuilder newTitle = new StringBuilder();
                        for (Text fragment : fragments) {
                            newTitle.append(fragment);
                        }
                        //高亮字段替换原来的字段
                        skuEsTo.setSkuTitle(newTitle.toString());
                    }
                }
                skuEsTos.add(skuEsTo);
            }
        }
        searchResp.setProducts(skuEsTos);
        //分类聚合信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResp.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResp.CatalogVo catalogVo = new SearchResp.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //获取子聚合 分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResp.setCatalogs(catalogVos);
        //品牌聚合信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResp.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResp.BrandVo brandVo = new SearchResp.BrandVo();
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            //获取子聚合 品牌名
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandName);
            //获取子聚合 品牌地址
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResp.setBrands(brandVos);
        //属性聚合信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResp.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResp.AttrVo attrVo = new SearchResp.AttrVo();
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //获取子聚合 属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //获取子聚合 属性值
            ParsedStringTerms attr_values_agg = bucket.getAggregations().get("attr_values_agg");
            List<String> attrValues = attr_values_agg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResp.setAttrs(attrVos);
        //封装分页信息
        searchResp.setPageNum(searchParam.getPageNum());
        long total = searchHits.getTotalHits().value;
        searchResp.setTotal(total);
        int totalPages = total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        searchResp.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResp.setPageNavs(pageNavs);
        //封装面包屑导航
        if (CollectionUtil.isNotEmpty(searchParam.getAttrs())) {
            List<SearchResp.NavVo> navs = searchParam.getAttrs().stream().map(attr -> {
                SearchResp.NavVo navVo = new SearchResp.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                //查询属性信息
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                //前台 所有属性id 判断是否回显属性信息
                searchResp.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    TypeReference<AttrResponseVo> typeReference = new TypeReference<AttrResponseVo>() {
                    };
                    AttrResponseVo data = r.getData("attr", typeReference);
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                String replace = replaceQueryString(searchParam, attr, "&attrs=");
                if (StringUtils.isNotBlank(replace)) {
                    navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                } else {
                    navVo.setLink("http://search.gulimall.com/list.html");
                }
                return navVo;
            }).collect(Collectors.toList());
            searchResp.setNavs(navs);
        }
        //封装面包屑导航 品牌
        if (CollectionUtil.isNotEmpty(searchParam.getBrandId())) {
            List<SearchResp.NavVo> navs = searchResp.getNavs();
            SearchResp.NavVo navVo = new SearchResp.NavVo();
            navVo.setNavName("品牌");
            R r = productFeignService.brandInfo(searchParam.getBrandId());
            if (r.getCode() == 0) {
                List<BrandRespVo> brand = r.getData("brand", new TypeReference<List<BrandRespVo>>() {
                });
                StringBuilder buffer = new StringBuilder();
                String replace = "";
                for (BrandRespVo brandRespVo : brand) {
                    buffer.append(brandRespVo.getName()).append(";");
                    replace = replaceQueryString(searchParam, brandRespVo.getBrandId() + "", "brandId=");
                }
                navVo.setNavValue(buffer.toString());
                if (StringUtils.isNotBlank(replace)) {
                    navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                } else {
                    navVo.setLink("http://search.gulimall.com/list.html");
                }
            } else {
                navVo.setNavValue(JSONUtil.toJsonStr(searchParam.getBrandId()));
            }
            navs.add(navVo);
            searchResp.setNavs(navs);
        }
        return searchResp;
    }

    private String replaceQueryString(SearchParam searchParam, String attr, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "Utf-8");
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //取消面包屑
        return searchParam.get_queryString().replace(key + encode, "");
    }

    /**
     * 首页/搜索页  构建检索请求
     * #模糊匹配,过滤(属性,分类,品牌,价格区间,库存),排序,分页,高亮,聚合
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //1.模糊匹配,过滤
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 bool-must 模糊匹配
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            // TODO: 2020/9/14 多条件匹配
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        //1.2 bool-filter  过滤三级分类
        if (searchParam.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //1.2 bool-filter  品牌id
        if (CollectionUtil.isNotEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //1.2 bool-filter  属性       attrs=1_安卓:其他&attrs=2_5G:6G
        if (CollectionUtil.isNotEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolBuild = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");//检索的属性值
                nestedBoolBuild.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolBuild.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个属性都要是一个新的NestedQueryBuilder
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolBuild, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //1.2 bool-filter  库存
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //1.2 bool-filter  价格区间     skuPrice 价格区间  1_500/_500/500_
        /*
         * {
         *           "range": {
         *             "skuPrice": {
         *               "gte": 10,
         *               "lte": 20
         *             }
         *           }
         * }
         */
        String skuPrice = searchParam.getSkuPrice();
        if (StringUtils.isNotBlank(skuPrice)) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = skuPrice.split("_");
            if (s.length == 2) {
                if (StringUtils.isEmpty(s[0])) {
                    rangeQuery.lte(s[1]);
                } else {
                    rangeQuery.gte(s[0]).lte(s[1]);
                }
            } else if (s.length == 1) {
                if (skuPrice.startsWith("_")) {
                    rangeQuery.lte(s[0]);
                } else if (skuPrice.endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        builder.query(boolQuery);
        //2.排序,分页,高亮
        // 2.1 排序 saleCount_asc/desc
        String sort = searchParam.getSort();
        if (StringUtils.isNotBlank(sort)) {
            String[] s = sort.split("_");
            SortOrder sortOrder = ("asc").equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], sortOrder);
        }
        // 2.2 分页  pageNum=1  from=(pageNum-1)*pageSize
        builder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        builder.size(EsConstant.PRODUCT_PAGESIZE);
        // 2.3 高亮
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }
        //1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合 name/img子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        builder.aggregation(brand_agg);
        //2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        builder.aggregation(catalog_agg);
        //3.属性聚合(应对扁平化处理:嵌入式) Nest
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_values_agg").field("attrs.attrValue").size(50));

        attr_agg.subAggregation(attr_id_agg);
        builder.aggregation(attr_agg);
        System.out.println(builder);
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);
    }
}
